<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>工程泛联客</title>
    <jsp:include page="../../../main/mp/inc.jsp"	/>
    <!-- 左侧panel事件 -->
    <script type="text/javascript">
        var ifApprove = "<s:property value="users.company.ifApprove" />";	//0不审批 1审批
        function panel_list_click(){
            $("a[key=ajax_negotiation_listview_actions_select]",$("#negotiation-listview-panel")).unbind('click').bind("click",function(e){
                var this_li = $(this).parent();
                var id = $(this_li).attr("id");
                $("#negotiationName").attr("value",$(this_li).attr("name"));
                $("#negotiationId").val(id);
                $( "#negotiationName" ).button( "refresh" );
                $("#clientName").html($(this_li).attr("clientName"));
                $("#visitman").val($(this_li).attr("visits"));
                $("#linkman").val($(this_li).attr("links"));
            });
        }
        function product_panel_list_click(){
            var product_panel = $("#product-listview-panel");
            $("a[key=ajax_listview_actions_select]",product_panel).unbind('click').bind("click",function(e){
                var this_li = $(this).parent();
                var id = $(this_li).attr("id");
                $("#productName").attr("value",$(this_li).attr("name"));
                $("#productId").val(id);
                $("#demand_num").val(1);
                $("#productName" ).button( "refresh" );


                //返回执行调出产品的价格
                var vActionUrl = "<%=path %>/mp/product!getProductById.action";
                $.ajax({url:vActionUrl,cache:false,dataType:"json",async:false,
                    data:{keyId:id},
                    success: function(data){
                        if(data.result.errorCode == 1 || data.result.errorCode == "1"){
                            var proPrice = data.data.dataRows[0].price;
                            var proCost  = data.data.dataRows[0].cost;
                            var proStock  = data.data.dataRows[0].stock;
                            $("#product_price").val(proPrice);
                            $("#product_cost").val(proCost);
                            $("#product_stock").val(proStock);
                            $("#demand_price").val(proPrice);
                            $("#demand_totalPrice").val(proPrice);
                            $("#demand_totalCost").val(proCost);
                        }
                    }
                });
            });
        }
    </script>

    <!-- 选择产品事件 -->
    <script type="text/javascript">
        function fn_calbyhand(){
            var totalPrice = parseFloat($("#demand_num").val())*parseFloat($("#demand_price").val()).toFixed(2);
            $("#demand_totalPrice").val(totalPrice.toFixed(2));
            var totalCost = parseFloat($("#demand_num").val())*parseFloat($("#product_cost").val()).toFixed(2);
            $("#demand_totalCost").val(totalCost.toFixed(2));
        }
    </script>
    <script>
        var isActiveMainPage = true;
        $(function(){
            bindClose();
            $("[data-role='navbar']").navbar();
            $("[data-role='header'], [data-role='footer']").toolbar();

            //btn_approve btn_cancel
            //$( "#comment-popup2" ).popup( "open" );
            $("#btn_approve").click(function(e){
                //判断人员不能为空
                if(!$("#approveMan").val()){
                    alert("请选择审批人！");
                    return false;
                }
                //赋值
                $("input[name=approveManId]").val($("#approveMan").val());
                $("input[name=comment]").val($("#comment").val());

                $( "#comment-popup2" ).popup( "close" );
                formSave();
            })

            $("#btn_cancel").click(function(e){
                $( "#comment-popup2" ).popup( "close" );
            })

            //加载洽谈页面
            loadListview($("#negotiation-listview-panel"),{},function(rdata){
                panel_list_click();
            });

            //clientName
            <s:if test="business==null">
            $("#negotiationName").click(function(){
                $( "#"+ $(this).attr("mp-panel-id") ).panel( "open" );
            })
            </s:if>


            $("#addProduct").click(function(){
                $( ":mobile-pagecontainer" ).pagecontainer( "load", "ajax-demand!edit.action" ,{type:'post',data:{},reload:true,loadMsgDelay:50});
            })

            $( ":mobile-pagecontainer" ).pagecontainer({
                load: function( event, ui ) {
                    setTimeout(function(){
                        //isActiveMainPage = false;
                        $( ":mobile-pagecontainer" ).pagecontainer( "change", "#product-page",{changeHash: false,reverse: true});
                    },500);
                }
            });
            //页面切换时，切换进产品信息和切换出产品信息都会调用，这里判断一下
            $( ":mobile-pagecontainer" ).on( "pagecontainertransition", function( event, ui ) {
                isActiveMainPage=(isActiveMainPage==true?false:true);
                //alert(isActiveMainPage)
                if(isActiveMainPage==true){
                    return false;
                }
                //处理panel搜索
                $("ul[data-input='#panel-product-search']").filterable({
                    filter:function(event, ui){
                        $(this).attr("mp-keyword",$("#panel-product-search").val());
                        loadListview($("#product-listview-panel"),{},function(rdata){
                            product_panel_list_click();
                        });
                    }
                });
                //处理金额计算事件
                $("#demand_num").on("change",function(){
                    fn_calbyhand();
                });
                $("#demand_price").on("change",function(){
                    fn_calbyhand();
                });

                var _apage = $( ":mobile-pagecontainer"  ).pagecontainer( "getActivePage" );

                var product_panel = $("#product-listview-panel");
                loadListview(product_panel,{},function(rdata){
                    product_panel_list_click();
                });

                //弹出产品列表
                $("#productName").unbind('click').bind("click",function(e){

                    $( "#"+ $(this).attr("mp-panel-id") ).panel( "open" );

                    e.preventDefault();
                    e.stopPropagation();
                })

                //循环得到data
                $("#demandId").data("totalCost",0.00);
                $("#demandId").data("totalPrice",0.00);

                //删除产品
                $("#product_page_delete").unbind('click').bind("click",function(e){
                    if(!confirm("确定删除该产品吗？保存后生效。")){
                        e.preventDefault();
                        e.stopPropagation();
                        return ;
                    }
                    var productId = $("#productId").val();
                    //$("#demandId").data(productId,{num:0,price:0,totalPrice:0,totalCost:0,requirements:""});
                    $("#demandId").removeData(productId);

                    fn_sumAllProducts(productId);
                    /*var _totalCost = parseFloat(0);
                     var _totalPrice = parseFloat(0);
                     var _totalDefaultPrice  = parseFloat(0);
                     var obj = $("#demandId").data();
                     for (var key in obj) {
                     if(key!="totalCost" && key!="totalPrice"){
                     //重新全部开始累加 alert(obj[key].num);
                     _totalCost += parseFloat(obj[key].totalCost);
                     _totalPrice += parseFloat(obj[key].totalPrice);

                     var _totalTmp = parseInt($("#demand_num").val())*parseFloat($("#product_price").val());
                     _totalDefaultPrice += parseFloat(_totalTmp);
                     }
                     }
                     _totalDefaultPrice = parseFloat(_totalDefaultPrice).toFixed(2);
                     _totalPrice = parseFloat(_totalPrice).toFixed(2);
                     _totalCost = parseFloat(_totalCost).toFixed(2);

                     $("#demandId").data("totalCost",_totalCost);
                     $("#demandId").data("totalPrice",_totalPrice);

                     //合计默认价格 合计成本
                     $("#totalDefaultMonty").val(_totalDefaultPrice);
                     //合计的小计金额
                     $("#totalMoney").val(_totalPrice);
                     $("#totalCost").val(_totalCost);
                     //计算，金额，成本，毛利
                     $("#money").val(_totalPrice);
                     $("#grossMargin").val(parseFloat(_totalPrice-_totalCost).toFixed(2));*/

                    //如果存在则，先remove掉
                    /*if($("#"+productId).length>0){
                     $("#"+productId).remove();
                     }*/

                    $("#product-list-ul").listview("refresh");
                    $("#product-list-ul").trigger( "updatelayout");
                    $(':mobile-pagecontainer').pagecontainer('change', '#main-page',{changeHash: false,reverse: true});
                    e.preventDefault();
                    e.stopPropagation();
                })
                //确认添加
                $("#product_page_confirm").unbind('click').bind("click",function(e){

                    if($("#demand_num").val() == ""){
                        alert("请填写件数!");
                        $("#demand_num").focus();
                        $("#demand_num").select();
                        return false;
                    }
                    if($("#demand_price").val() == ""){
                        alert("请填写单价!");
                        $("#demand_price").focus();
                        $("#demand_price").select();
                        return false;
                    }
                    if(parseInt($("#demand_num").val()) > parseInt($("#product_stock").val())){
                        alert("填写的件数不能大于库存量!");
                        $("#demand_num").focus();
                        $("#demand_num").select();
                        return false;
                    }
                    //$("#demand_totalPrice").val(parseInt($("#demand_num").val())*parseFloat($("#demand_price").val()));
                    //$("#demand_totalCost").val(parseInt($("#demand_num").val())*parseFloat($("#product_cost").val()));

                    fn_calbyhand();
                    //alert($("form#demand-form").serialize())
                    //$( ":mobile-pagecontainer" ).pagecontainer( "change", "#product-page", { dataUrl : "ajax-demand!edit.action",reload:true } );
                    var productId = ($("#productId").val());
                    var productName = ($("#productName").val());
                    var product_price = $("#product_price").val();
                    var product_cost = $("#product_cost").val();
                    var num = ($("#demand_num").val());
                    var price = ($("#demand_price").val());
                    var totalPrice = ($("#demand_totalPrice").val());
                    var totalCost = ($("#demand_totalCost").val());
                    var demand_requirements = $("#demand_requirements").val();
                    //$("#totalMoney").val(parseInt($("#demand_num").val())*parseFloat($("#product_price").val()));

                    $("#demandId").data(productId,{keyId:'',num:num,price:price,totalPrice:totalPrice,totalCost:totalCost,requirements:demand_requirements,product_price:product_price});

                    fn_sumAllProducts(productId);
                    /*//合计成本、合计可编辑价格、合计默认价格
                     var _totalCost = parseFloat(0);
                     var _totalPrice = parseFloat(0);
                     var _totalDefaultPrice = parseFloat(0);

                     var obj = $("#demandId").data();

                     for (var key in obj) {
                     if(key!="totalCost" && key!="totalPrice"){
                     //重新全部开始累加 alert(obj[key].num);
                     _totalCost += parseFloat(obj[key].totalCost);
                     _totalPrice += parseFloat(obj[key].totalPrice);
                     //var _totalTmp = parseFloat($("#demand_num").val())*parseFloat($("#product_price").val());
                     var _totalTmp = parseFloat(obj[key].num)*parseFloat(obj[key].product_price);
                     _totalDefaultPrice += parseFloat(_totalTmp);

                     }
                     }

                     _totalPrice = parseFloat(_totalPrice).toFixed(2);
                     _totalCost = parseFloat(_totalCost).toFixed(2);

                     $("#demandId").data("totalCost",_totalCost);
                     $("#demandId").data("totalPrice",_totalPrice);

                     //合计默认总价 合计成本
                     $("#totalDefaultMonty").val(_totalDefaultPrice.toFixed(2));

                     $("#totalMoney").val(_totalPrice);
                     $("#totalCost").val(_totalCost);

                     //计算，金额，成本，毛利
                     $("#money").val(_totalPrice);
                     //$("#projectedCost").val(_totalCost);
                     $("#grossMargin").val(parseFloat(_totalPrice-_totalCost).toFixed(2));

                     //alert($("#demandId").data(productId).num)
                     //关闭product - page
                     //$("#product-page").remove();
                     //$("#main").addClass("ui-page-active");
                     //$( ":mobile-pagecontainer" ).pagecontainer( "change","#main-page",{reload:true });
                     */
                    //如果存在则，先remove掉
                    /*if($("#"+productId).length>0){
                     $("#"+productId).remove();
                     }*/

                    //回调+创建列表
                    var tmplist = '<li id="'+productId+'"><a href="javascript:fn_productEdit(\''+productId+'\')" mp-url=""><h3> '+productName+' </h3><h4>[总价：'+totalPrice+'][总成本：'+totalCost+']</h4><p>[数量：'+num+'][单价：'+price+'][单位成本：'+product_cost+']</p></a></li>';
                    $(tmplist).appendTo($("#product-list-ul"));
                    $("#product-list-ul").listview("refresh");
                    $("#product-list-ul").trigger( "updatelayout");

                    $(':mobile-pagecontainer').pagecontainer('change', '#main-page',{changeHash: false,reverse: true});
                    e.preventDefault();
                    e.stopPropagation();

                })
            });


            var currYear = (new Date()).getFullYear();
            var opt={};
            opt.date = {preset : 'date'};
            //opt.datetime = { preset : 'datetime', minDate: new Date(2012,3,10,9,22), maxDate: new Date(2014,7,30,15,44), stepMinute: 5  };
            opt.datetime = {preset : 'datetime'};
            opt.time = {preset : 'time'};
            opt.default = {
                theme: 'android-ics light', //皮肤样式
                display: 'modal', //显示方式
                mode: 'scroller', //日期选择模式
                animate:'swing',
                lang:'zh',
                startYear:currYear - 10, //开始年份
                endYear:currYear + 10 //结束年份
            };
            var optDateTime = $.extend(opt['datetime'], opt['default']);
            $("#deliveryDate").val('<s:date name="business.deliveryDate" format="yyyy-MM-dd" />').scroller('destroy').scroller($.extend(opt['date'], opt['default']));
            $("#preDate").val('<s:date name="business.preDate" format="yyyy-MM-dd" />').scroller('destroy').scroller($.extend(opt['date'], opt['default']));

            $("#btn-save-common").click(function(e){
                //判断是否已经成交
                /*var stepId = $("#business_step_id").val();
                 if(stepId == $("#stepId").val()){
                 var str = "请确认纸质合同是否已签订，业务阶段为成交时，系统会根据该业务自动创建成交记录（注：合同金额及产品将不可更改）。";
                 $("#popup_msg").text(str);
                 $("#popup_div").popup("open");
                 setTimeout("close_popup()", 3000 );
                 }else{
                 save_from();
                 }*/
                //字符串对比
                if($("#businessSuccess").val() == "true"){

                }
                save_from();
            });

            //组装 $("#demandId").data();
            $.getJSON('<%=path %>/mp/ajax-demand!getListMap.action?keyId=<s:property value="business.id" />', function(data) {
                if(data.result.errorCode == 1 || data.result.errorCode == "1"){
                    $(data.data.demands).each(function(i,v){
                        var productId = v.product.id;
                        var productName = v.product.name;
                        var product_cost = v.cost;
                        var product_price = v.price;
                        var keyId = v.id;
                        var num = v.num;
                        var price = v.price;
                        var totalPrice = v.totalPrice;
                        var totalCost = v.totalCost;
                        var demand_requirements = v.requirements;

                        $("#demandId").data(productId,{keyId:keyId,num:num,price:price,totalPrice:totalPrice,totalCost:totalCost,requirements:demand_requirements,product_price:product_price});
                        $("#demandPreId").data(productId,{keyId:keyId,num:num,price:price,totalPrice:totalPrice,totalCost:totalCost,requirements:demand_requirements,product_price:product_price});
                    })
                }
            });
        });

        //合计#demandId的data属性里面所有的数据的金额
        function fn_sumAllProducts(productId){
            //合计成本、合计可编辑价格、合计默认价格
            var _totalCost = parseFloat(0);
            var _totalPrice = parseFloat(0);
            var _totalDefaultPrice = parseFloat(0);

            var obj = $("#demandId").data();
            for (var key in obj) {
                if(key!="totalCost" && key!="totalPrice"){
                    //重新全部开始累加 alert(obj[key].num);
                    _totalCost += parseFloat(obj[key].totalCost);
                    _totalPrice += parseFloat(obj[key].totalPrice);
                    var _totalTmp = parseFloat(obj[key].num)*parseFloat(obj[key].product_price);
                    _totalDefaultPrice += parseFloat(_totalTmp);
                }
            }
            _totalPrice = parseFloat(_totalPrice).toFixed(2);
            _totalCost = parseFloat(_totalCost).toFixed(2);

            $("#demandId").data("totalCost",_totalCost);
            $("#demandId").data("totalPrice",_totalPrice);

            //合计默认总价 合计成本
            $("#totalDefaultMonty").val(_totalDefaultPrice.toFixed(2));
            $("#totalMoney").val(_totalPrice);
            $("#totalCost").val(_totalCost);
            //计算，金额，成本，毛利
            $("#money").val(_totalPrice);
            $("#grossMargin").val(parseFloat(_totalPrice-_totalCost).toFixed(2));

            //如果存在则，先remove掉
            if($("#"+productId).length>0){
                $("#"+productId).remove();
            }
        }
        //列表点击后编辑产品
        function fn_productEdit(id){
            var productId = id;
            var obj = $("#demandId").data();
            //利用data把内容传递过去
            var vdata = obj[productId];
            $( ":mobile-pagecontainer" ).pagecontainer( "load", "ajax-demand!edit.action?productId=" + productId ,{type:'post',data:vdata,reload:true,loadMsgDelay:50});
        }

        //审批自动选择上级负责人
        function checkApprove(){
            $("#approveMan").val("");
            $("#comment").val("");
            if(ifApprove=="0"){
                return false;
            }
            if($("#totalMoney").val()==""){
                $("#totalMoney").val(0);
            }
            //判断是否需要审批
            //填写的总金额和计算的默认的总金额不相等 或者  单个产品：如果产品不存在，单个产品的单价和默认的单价相比，否则和修改前的单价做比较 （三个条件）
            //----产品发生变化时 和默认总价相比，否则和上次总价相比----
            var flag = 0;
            if($("input[name=keyId]").val()==""){
                //新建
                var obj = $("#demandeId").data();
                for (var key in obj) {
                    if(key!="totalCost" && key!="totalPrice"){
                        if(parseInt(obj[key].num) > 0){
                            //product_price
                            var product_price = parseFloat(obj[key].product_price).toFixed(2);
                            var price = parseFloat(obj[key].price).toFixed(2);
                            if(price != product_price){
                                flag = 1;
                                break;
                            }
                        }
                    }
                }
                //总价
                var money = parseFloat($("#money").val()).toFixed(2);
                var totalMoney = parseFloat($("#totalMoney").val()).toFixed(2);
                if(money != totalMoney){
                    flag = 1;
                }
            }else{
                //编辑
                //原历史总价格 totalPreMoney
                //判断是否产品发生变化
                var objPre = $("#demandPreId").data();
                var obj = $("#demandId").data();
                var modifyFlag = 0;
                var preNum = 0;
                var nowNum = 0;
                for (var key in objPre) {
                    preNum++;
                }
                for (var key in objPre) {
                    nowNum++;
                }
                if(preNum==nowNum){
                    //产品总数相等
                    //判断当前产品在历史中是否存在 !("key" in obj) // true if "key" doesn't exist in object
                    for (var key in obj) {
                        if(key!="totalCost" && key!="totalPrice"){
                            if(!(key in objPre)){
                                var money = parseFloat($("#money").val()).toFixed(2);
                                var totalMoney = parseFloat($("#totalMoney").val()).toFixed(2);
                                if(money != totalMoney){
                                    flag = 1;
                                    break;
                                }
                            }else{
                                //比较两次产品输入的单价
                                var pricePre = parseFloat(objPre[key].price).toFixed(2);
                                var price = parseFloat(obj[key].price).toFixed(2);
                                if(price != pricePre){
                                    flag = 1;
                                    break;
                                }
                            }
                        }
                    }
                    //价格和上次价格相比
                    var money = parseFloat($("#money").val()).toFixed(2);
                    var totalMoney = parseFloat($("#totalPreMoney").val()).toFixed(2);
                    //alert(flag + " " + money + " " + totalMoney)
                    if(parseFloat(money) != parseFloat(totalMoney)){
                        flag = 1;
                    }

                }else{
                    //产品发生变化，比较当前总价和原始总价
                    var money = parseFloat($("#money").val()).toFixed(2);
                    var totalMoney = parseFloat($("#totalMoney").val()).toFixed(2);
                    if(money != totalMoney){
                        flag = 1;
                    }
                }
            }
            if(flag == 1 ){
                $( "#comment-popup2" ).popup( "open" );
                return true;
            }else{
                return false;
            }
        }

        //form保存操作
        function formSave(){
            if($("#grossMargin").val()=="NaN"){
                $("#grossMargin").val(0);
            }
            if($("#money").val()==""){
                $("#money").val(0);
            }
            if($("#totalCost").val()==""){
                $("#totalCost").val(0);
            }
            if($("#totalDefaultMonty").val() == ""){
                $("#totalDefaultMonty").val(0);
            }

            $("#projectedCost").val($("#totalCost").val());
            $("#btn-save-common").hide();
            //$("#btn-save-common").attr("disabled","disabled");
            $.mobile.loading( "show", {
                text: "正在保存，请稍后...",
                textVisible: true,
                theme: "b",
                textonly: false,
                html: ""
            });
            $.ajax({
                type: "POST",
                url: $("form#form-common").attr("action"),
                cache:false,dataType:"json",
                data: $("form#form-common").serialize(),
                async:true,
                success: function(data){
                    hide();
                    if(data.result.errorCode == 1 || data.result.errorCode == "1"){
                        unbindClose();
                        alert(data.result.errorMessage)	 ;
                        if(data.data.key == "business"){
                            location.replace("business!read.action?keyId=" + data.data.value);
                        }else{
                            location.replace("contract!edit.action?keyId=" + data.data.value);
                        }
                    }else{
                        $("#btn-save-common").show();
                        alert(data.result.errorMessage)	 ;
                        //$.mobile.changePage("content/loginfalse.html","slidedown", true, true);
                    }
                }
            });
        }
    </script>
    <!-- panel查询 -->
    <script type="text/javascript">
        $(function(){
            $("ul[data-input=#panel-search]").on("filterablebeforefilter",function(event){

                $(this).attr("mp-keyword",$("#panel-search").val());
                loadListview($("#negotiation-listview-panel"),{},function(rdata){
                    panel_list_click();
                });
            });

        });

    </script>

    <!-- 弹出提示信息 -->
    <script type="text/javascript">

        function close_popup(){
            $("#popup_div").popup("close");
            setTimeout("save_from()", 300 );
        }
        function save_from(){
            //计算毛利
            //alert($("#money").val() +""+ $("#totalCost").val() +""+ (parseFloat($("#money").val()) - parseFloat($("#totalCost").val())))
            var gross = parseFloat($("#money").val()) - parseFloat($("#totalCost").val());
            $("#grossMargin").val(parseFloat(gross).toFixed(2));

            if($("#grossMargin").val()=="NaN"){
                $("#grossMargin").val(0);
            }
            if($("#money").val()==""){
                $("#money").val(0);
            }
            if($("#totalCost").val()==""){
                $("#totalCost").val(0);
            }

            if(!confirm("确定提交保存吗？")){
                return ;
            }

            //计算提交的内容，读取
            var obj = $("#demandId").data();
            var rowDatas = [];
            for (var key in obj) {
                if(key!="totalCost" && key!="totalPrice"){
                    if(parseInt(obj[key].num) > 0){
                        var rowData = {keyId:obj[key].keyId,productId:key, num:obj[key].num, price:obj[key].price, totalPrice:obj[key].totalPrice, totalCost:obj[key].totalCost,requirements:obj[key].requirements};
                        rowDatas.push(rowData);
                    }
                }
            }
            var demandList = {demandList:rowDatas};
            if(rowDatas.length>0){
                $("#demandId").val(JSON.stringify(demandList));
            }

            //当前操作需要审批
            /*if(checkApprove()){
             e.preventDefault();
             e.stopPropagation();
             return ;
             }
             formSave();*/
            ajaxCheckApproce();
        }

        //审批条件后台验证
        function ajaxCheckApproce(){
            if($("#grossMargin").val()=="NaN"){
                $("#grossMargin").val(0);
            }
            if($("#money").val()==""){
                $("#money").val(0);
            }
            if($("#totalCost").val()==""){
                $("#totalCost").val(0);
            }
            if($("#totalDefaultMonty").val() == ""){
                $("#totalDefaultMonty").val(0);
            }
            $("#projectedCost").val($("#totalCost").val());
            $.ajax({
                type: "POST",
                url: "business!ifNeedApprove.action",
                cache:false,dataType:"json",
                data: {businessMoney:$("#money").val(),demandListJson:$("#demandId").val()},
                async:true,
                success: function(data){
                    if(data.result.errorCode == 1 || data.result.errorCode == "1"){
                        if(data.result.errorMessage == "0"){
                            //不审批
                            formSave();
                        }else{
                            //审批
                            $( "#comment-popup2" ).popup( "open" );
                        }
                    }else{
                        alert(data.result.errorMessage)	 ;
                    }
                }
            });
        }
    </script>
</head>
<body>
<div data-role="page" id="main-page">
    <div data-role="header" data-position="fixed" data-theme="a">
        <%--<a href="business!list.action" data-ajax="false" id="" class="ui-btn ui-btn-left ui-icon-bars ui-corner-all ui-btn-icon-left">视图</a>
         --%><h1 style="float:left;margin: 0 10px;"><i class="fa fa-check-square"></i> <s:if test="business==null">新建</s:if><s:else>编辑</s:else>业务信息</h1>
        <a href="#" id="btn-save-common" class="ui-btn ui-btn-right ui-icon-check ui-corner-all ui-btn-icon-left">保存</a>
    </div><!-- /header -->
    <div class="ui-content jqm-content jqm-fullwidth" role="main">
        <form method="post" id="form-common" action="business!save.action" data-ajax="false">
            <input type="hidden" name="keyId" value="<s:property value="business.id" />">
            <input type="hidden" name="businessSuccess" id="businessSuccess" value="<s:property value="businessSuccess" />">
            <input type="hidden" name="totalDefaultMonty" id="totalDefaultMonty" value="">

            <s:if test="business==null && negotiation==null">
                <div class="ui-field-contain">
                    <fieldset data-role="controlgroup">
                        <legend>洽谈信息：</legend>
                        <input type="button" data-mini="true" mp-panel-id="negotiation-listview-panel" data-icon="carat-r" data-iconpos="right" name="negotiationName" id="negotiationName" value="请选择一个洽谈...">
                        <input type="hidden" name="negotiationId" id="negotiationId" value="">
                    </fieldset>
                </div>
            </s:if>
            <s:else>
                <s:if test="business == null">
                    <div class="ui-field-contain">
                        <fieldset data-role="controlgroup">
                            <legend>洽谈信息：</legend>
                            <s:property value="negotiation.subject" />
                            <input type="hidden" name="negotiationId" id="negotiationId" value="<s:property value="negotiation.id" />">
                        </fieldset>
                    </div>
                </s:if>
            </s:else>

            <div class="ui-field-contain">
                <label for="name">客户名称：</label>
                <span id="clientName"><s:if test="negotiation==null"><s:property value="business.client.name" /></s:if><s:else><s:property value="negotiation.client.name" /></s:else></span>
            </div>
            <s:if test="business.id != null">
                <div class="ui-field-contain">
                    <label >业务编号：</label>
                    <s:property value="business.no" />
                </div>
            </s:if>
            <div class="ui-field-contain">
                <label for="name">业务名称 *：</label>
                <input type="text" name="name" id="name" placeholder="请填写业务名称，不能为空" value="<s:property value="business.name" />">
            </div>
            <div class="ui-field-contain">
                <label for="salesAreaId">销售区域：</label>
                <select name="salesAreaId" id="salesAreaId" data-native-menu="true" data-mini="true">
                    <s:iterator value="listSalesArea" id="list">
                        <option value="<s:property value="#list.id"/>"  <s:if test="#list.id == business.salesArea.id"> selected="selected" </s:if> ><s:property value="#list.sname" /></option>
                    </s:iterator>
                </select>
            </div>
            <div class="ui-field-contain">
                <label for="stepId">业务阶段 *：</label>
                <select name="stepId" id="stepId" data-native-menu="true" data-mini="true">
                    <s:iterator value="listStep" id="list">
                        <option value="<s:property value="#list.id"/>"  <s:if test="#list.id == business.step.id"> selected="selected" </s:if> ><s:property value="#list.sname" /></option>
                    </s:iterator>
                </select>
            </div>
            <div class="ui-field-contain">
                <label for="possibilityId">可能性 *：</label>
                <select name="possibilityId" id="possibilityId" data-native-menu="true" data-mini="true">
                    <s:iterator value="listPossibility" id="list">
                        <option value="<s:property value="#list.id"/>"  <s:if test="#list.id == business.possibility.id"> selected="selected" </s:if> ><s:property value="#list.sname" /></option>
                    </s:iterator>
                </select>
            </div>
            <div class="ui-field-contain">
                <label for="preDate">可签时间 *：</label>
                <input type="text" name="preDate" id="preDate" placeholder="请选择预计签约时间，不能为空" value="<s:date name="business.preDate" format="yyyy-MM-dd" />">
            </div>

            <div class="ui-field-contain">
                <label for="others">业务对象：</label>
                <s:if test="from == ''">
                    <s:iterator value="business.linkman" id="list"><s:property value="#list.name"/> </s:iterator>
                </s:if>
                <s:else>
                    <s:iterator value="negotiation.linkman" id="list"><s:property value="#list.name"/> </s:iterator>
                </s:else>
            </div>

            <div class="ui-field-contain">
                <label for="visitman">参与人员：</label>
                <select name="visitman" id="visitman" multiple="multiple" data-native-menu="false" data-mini="true">
                    <option>请选择我方参与人员...</option>
                    <s:iterator value="visitmanList" id="list">
                        <option value="<s:property value="#list.id"/>" <s:property value="#list.selected"/>><s:property value="#list.name" /></option>
                    </s:iterator>
                </select>
            </div>
            <hr />
            <div class="ui-field-contain">
                <label for="money">合同金额：</label>
                <input type="number" name="money" id="money" value="<s:property value="business.money" />">
            </div>
            <div class="ui-field-contain">
                <label class="label-readonly">合计金额(元)：</label>
                <input readonly  type="text" name="totalMoney" id="totalMoney" value="<s:property value="totalMoney" />" />
            </div>
            <div class="ui-field-contain">
                <label class="label-readonly">合计成本(元)：</label>
                <input readonly type="text" name="totalCost" id="totalCost" value="<s:property value="totalCost" />">
            </div>

            <div class="ui-field-contain">
                <label class="label-readonly" for="grossMargin">毛利：</label>
                <input type="text" readonly name="grossMargin" id="grossMargin" value="<s:property value="business.grossMargin" />">
            </div>
            <div class="ui-field-contain">
                <label for="deliveryDate">预计交期：</label>
                <input type="text" name="deliveryDate" id="deliveryDate" value="<s:date name="business.deliveryDate" format="yyyy-MM-dd" />">
            </div>
            <div class="ui-field-contain">
                <label for="others">其他描述：</label>
                <textarea cols="40" rows="8" name="others" id="others"><s:property value="business.others" /></textarea>
            </div>
            <!-- 产品合计 -->
            <input type="button" data-mini="true" data-theme="b" mp-panel-id="product-listview-panel" data-icon="plus" data-iconpos="right" name="addProduct" id="addProduct" value="添加产品">
            <input type="hidden" name="demandListJson" id="demandId" data="" value="">
            <input type="hidden" id="demandPreId" data="" value="">
            <input type="hidden" id="totalPreMoney" value="<s:property value="business.money" />" />
            <input type="hidden" name="approveManId" value="" />
            <input type="hidden" name="comment" value="" />
            <input type="hidden" name="projectedCost" id="projectedCost" value="" />

            <h4>产品明细</h4>
            <!-- 产品列表 -->
            <ul data-role="listview" data-theme="a" data-dividertheme="b" id="product-list-ul" data-inset="true">
                <s:iterator value="business.demand" id="list">
                    <s:if test="#list.state.toString() == 'Enable'">
                        <li id="<s:property value="#list.product.id"/>"><a data-ajax="false" href="javascript:fn_productEdit('<s:property value="#list.product.id"/>')" mp-url="business!read.action?keyId=<s:property value="#list.id"/>">
                            <h3> <s:property value="#list.product.name" /> </h3>
                            <h4>[总价：<s:property value="#list.totalPrice" />][总成本：<s:property value="#list.totalCost" />]</h4>
                            <p>[数量：<s:property value="#list.num" />][单价：<s:property value="#list.price" />][单位成本：<s:property value="#list.cost" />]</p>
                        </a>
                        </li>
                    </s:if>
                </s:iterator>
            </ul>
            <!-- 时间戳 -->
            <input  type="hidden" name="timestamp" id="timestamp" value=""/>
            <input type="hidden" name="business_step_id" id="business_step_id" value="<s:property value="business_step_id"/>">
        </form>

        <div data-role="popup" id="comment-popup2" data-theme="a" class="" data-history="false" data-corners="false" data-overlay-theme="b">
                    <div style="padding:0 8px;">
            <p>价格与默认价格不匹配或者价格发生修改，需要申请审批！</p>
            <textarea cols="40" rows="8" name="comment2" id="comment" placeholder="请填写您的批注信息"></textarea>
            <select name="approveManId2" id="approveMan" data-native-menu="true" data-mini="true">
                <option>请选择审批人员...</option>
                <s:iterator value="usersList" id="list">
                    <option value="<s:property value="#list.id"/>" <s:property value="#list.selected"/>><s:property value="#list.name" /></option>
                </s:iterator>
            </select>
            <button type="button" id="btn_cancel"  class="ui-btn ui-btn-inline ui-corner-all ui-shadow  ui-btn-icon-left ui-icon-forbidden ui-mini">取消</button>
            <button type="button" id="btn_approve" class="ui-btn ui-btn-inline ui-corner-all ui-shadow  ui-btn-icon-left ui-icon-check ui-mini">提交审批</button>
        </div>
        </div>
    </div><!-- /content -->
    <!-- 通用的弹出框div -->
    <div data-role="popup" id="popup_div">
        <p id="popup_msg"></p>
    </div>
    <!-- 客户信息通用选择框 -->
    <div data-role="panel" data-position="right" data-position-fixed="true" data-display="overlay" data-theme="a" id="negotiation-listview-panel"
         mp-url="ajax-negotiation!listview.action" >
        <form class="ui-filterable">
            <input data-type="search" placeholder="按客户名称搜索"  id="panel-search"/>
        </form>
        <ul data-role="listview" data-theme="a" data-dividertheme="b"
            mp-page="1" mp-keyword=""
            data-filter-placeholder="按客户名称搜索" data-input="#panel-search" data-filter="true">

        </ul>
        <hr/>
        <div>
            <a href="#" key="prePage" class="ui-btn ui-btn-icon-notext ui-corner-all ui-shadow ui-mini ui-btn-inline ui-icon-carat-l "> 上一页</a>
            <a href="#" key="nextPage" class="ui-btn ui-btn-icon-notext ui-corner-all ui-shadow ui-mini ui-btn-inline ui-icon-carat-r ">下一页 </a>
				<span class="ui-btn-inline">
					页数  <span key="pageNumber"></span>/<span key="pageCount"></span> 共<span key="totalCount"></span>条
				</span>
        </div>
    </div><!-- /panel -->
</div><!-- /page -->

</body>
</html>